package com.shbaiche.bifenba.util;

import android.app.*;
import android.app.TaskStackBuilder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.*;
import android.text.Html;
import android.text.TextUtils;

import com.meiqia.core.MQManager;
import com.meiqia.core.bean.MQAgent;
import com.meiqia.core.bean.MQMessage;
import com.meiqia.core.callback.OnClientOnlineCallback;
import com.meiqia.core.callback.OnEndConversationCallback;
import com.meiqia.core.callback.OnGetMQClientIdCallBackOn;
import com.meiqia.core.callback.SimpleCallback;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.model.base.Passport;
import com.shbaiche.bifenba.ui.MainTabActivity;
import com.shbaiche.bifenba.ui.my.CustomizedMQConversationActivity;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by wanghong on 2017/11/27.
 */

public class MeiqiaUtils {
    public static final int MEIQIA_REQUESTCODE = 50123;
    public void openService(final Activity activity){
        MQConfig.isShowClientAvatar = true;

        String clientId = getClientId();
        if(clientId!=null && clientId.length()>0){
            changeId(activity,clientId);

            Intent intent = new MQIntentBuilder(activity,CustomizedMQConversationActivity.class)
                    .setClientInfo(getUserInfo())
                    .setClientId(clientId)
                    .build();
            activity.startActivityForResult(intent,MEIQIA_REQUESTCODE);
        }else{
            MQManager.getInstance(activity).createMQClient(new OnGetMQClientIdCallBackOn() {
                @Override
                public void onSuccess(String s) {
                    Passport passport = App.getPassport();
                    if(passport!=null){
                        SystemUtil.savePreference("DEFID_"+passport.getBetCardNo(),s);
                    }else{
                        SystemUtil.savePreference("DEFID",s);
                    }

                    changeId(activity,s);

                    Intent intent = new MQIntentBuilder(activity,CustomizedMQConversationActivity.class)
                            .setClientInfo(getUserInfo())
                            .setClientId(s)
                            .build();
                    activity.startActivityForResult(intent,MEIQIA_REQUESTCODE);

                }

                @Override
                public void onFailure(int i, String s) {

                }
            });
        }


    }

    private void changeId(Activity activity, String nid){
        String lastId = SystemUtil.loadPreference("DEFID_LAST");
        if(lastId!=null && lastId.length()>0 && !lastId.equals(nid)) {
            MQManager.getInstance(activity).endCurrentConversation(null);
        }
        SystemUtil.savePreference("DEFID_LAST",nid);
    }

    private String getClientId(){
        Passport passport = App.getPassport();
        String id =  null;
        if(passport!=null){
            id = SystemUtil.loadPreference("DEFID_"+passport.getBetCardNo());
        }else{
            id = SystemUtil.loadPreference("DEFID");
        }
        return id;
    }

    private HashMap<String, String> getUserInfo(){
        final HashMap<String, String> info = new HashMap<>();
        Passport passport = App.getPassport();
        if(passport!=null){
            MQConfig.isShowClientAvatar = true;
            String userName= passport.getUserName();
            if(StringUtil.isMobile(userName)){
                userName = StringUtil.phoneToShiel(userName);
            }

            String mobile= passport.getMobile();
            if(StringUtil.isMobile(mobile)){
                mobile = StringUtil.phoneToShiel(mobile);
            }

            info.put("name", userName);
            info.put("avatar", passport.getPhotoPath());
            info.put("gender", "");
            info.put("tel", mobile);



            return info;
        }else{
            MQConfig.isShowClientAvatar = false;
            info.put("name", "匿名用户");
            info.put("avatar", "");
            info.put("gender", "");
            info.put("tel", "");
            return info;
        }

    }
    NotificationCompat.Builder mBuilder;
    NotificationManager mNotificationManager;

    public void show(Activity activity,String msg){
        initNotify(activity);
        NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle();

        textStyle.bigText(Html.fromHtml(msg));
        mBuilder.setContentTitle("新消息")
                .setContentText(""+msg)
//				.setNumber(number)//显示数量
                .setStyle(textStyle)//设置风格
                .setTicker("");// 通知首次出现在通知栏，带上升动画效果的
        mBuilder.setAutoCancel(true);

        Intent intent = new MQIntentBuilder(activity,CustomizedMQConversationActivity.class)
                .build();

        //intent = new Intent(activity,MainTabActivity.class);
        //intent.putExtra("MQ",true);


//        android.support.v4.app.TaskStackBuilder stackBuilder = android.support.v4.app.TaskStackBuilder.create(HappyApp.getContext());
//        //为点击通知后打开的页面设定 返回 页面。（在manifest中指定）
//        stackBuilder.addParentStack(MainTabActivity.class);
//        stackBuilder.addNextIntent(intent);
//
//        PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
          PendingIntent pIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);


        mBuilder.setContentIntent(pIntent);

        mNotificationManager.notify(55678, mBuilder.build());


    }

    public PendingIntent getDefalutIntent(Context context, int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, new Intent(), flags);
        return pendingIntent;
    }
    private void initNotify(Context context) {
        if (mBuilder == null) {
            mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setContentTitle("")
                    .setContentText("")
                    .setContentIntent(getDefalutIntent(context, Notification.FLAG_AUTO_CANCEL))
//				.setNumber(number)//显示数量
                    .setTicker("")//通知首次出现在通知栏，带上升动画效果的
                    .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示
                    .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
//				.setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                    .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
                    .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合：
                    //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                    .setSmallIcon(R.drawable.ic_launcher);
            //.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.drawable.ic_quick_login_weixin));
        }

        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
    }


}
